from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from plone.app.layout.viewlets.common import ViewletBase

from zope.component import getMultiAdapter
from Products.CMFCore.utils import getToolByName
from zope.app.component.hooks import getSite

from AccessControl import getSecurityManager

from collective.plonetruegallery.utils import getGalleryAdapter
from collective.plonetruegallery.settings import GallerySettings

import re


class actions(ViewletBase):
    """viewlet de site_actions"""
    render = ViewPageTemplateFile('templates/actions.pt')
    def update(self):
      context_state = getMultiAdapter((self.context, self.request),
                                        name=u'plone_context_state')
      self.site_actions = context_state.actions('site_actions')


class logoViewlet(ViewletBase):
    """logo viewlet"""
    render = ViewPageTemplateFile('templates/logo.pt')
    def update(self):
        super(logoViewlet, self).update()

        portal = self.portal_state.portal()
        logoName = portal.restrictedTraverse('base_properties').logoName
        self.logo_tag = portal.restrictedTraverse(logoName).tag()

        self.portal_title = self.portal_state.portal_title()
        miUtils = utils(self.context)
        catalog = miUtils.catalog
        portal = miUtils.portal
        portal = portal.getId()
        path = path = '/'+portal+'/logo'
        self.result = catalog.searchResults(path={'query':path,'depth':1},portal_type='Image',Title='logo.png')


class search(ViewletBase):
    """Viewlet search box """
    render = ViewPageTemplateFile('templates/search.pt')
    def update(self):
        super(search,self).update()
        
        context_state = getMultiAdapter((self.context, self.request),
                                            name=u'plone_context_state')
        props = getToolByName(self.context,'portal_properties')
        livesearch = props.site_properties.getProperty('enable_livesearch',False)
        if livesearch:
            self.search_input_id = "searchGadget"
        else:
            self.search_input_id = ""

        folder = context_state.folder()
        self.folder_path = '/'.join(folder.getPhysicalPath())


class personalBar(ViewletBase):
    """Viewlet personal_bar"""
    render =  ViewPageTemplateFile('templates/personal.pt')
    def update(self):
        super(personalBar,self).update()

        context_state = getMultiAdapter((self.context,self.request),
                                        name=u'plone_context_state')
        tools = getMultiAdapter((self.context,self.request),
                                name=u'plone_tools')
        sm = getSecurityManager()
        self.user_actions = context_state.actions().get('user',None)

        plone_utils = getToolByName(self.context,'plone_utils')
        self.getIconFor = plone_utils.getIconFor

        self.anonymous = self.portal_state.anonymous()

        if not self.anonymous:
            member = self.portal_state.member()
            userid = member.getId()

            if sm.checkPermission('Portlets: Manage own portlets', self.context):
                self.homelink_url = self.navigation_root_url + '/dashboard'
            else:
                self.homelink_url = self.navigation_root_url + \
                '/personalize_form'
                
            member_info = tools.membership().getMemberInfo(member.getId())
            # member_info is None if there's no Plone user object, as when
            # using OpenID.
            if member_info:
                fullname = member_info.get('fullname','')
            else:
                fullname = None
            if fullname:
                self.user_name = fullname
            else:
                self.user_name = userid


class pathBar(ViewletBase):
    """viewlet para menu.path_bar"""
    render = ViewPageTemplateFile('templates/path.pt')
    def update(self):
        super(pathBar,self).update()
        self.is_rtl = self.portal_state.is_rtl()
        breadcrumbs_view = getMultiAdapter((self.context,self.request),
                                            name=u'breadcrumbs_view')
        self.breadcrumbs = breadcrumbs_view.breadcrumbs()

        portal = getSite()
        self.portalUrl = portal.absolute_url()


class menuTop(ViewletBase):
    """Viewlet menu.top"""
    render = ViewPageTemplateFile('templates/menuTop.pt')

    def update(self):
        context_state = getMultiAdapter((self.context,self.request),
                                            name=u'plone_context_state')
        self.menu = context_state.actions('menu_top')

#    def contenido(self,item):
#        object = getattr(self.context,item)
#        result = object.getFolderContents(contentFilter={"portal_type":'Folder'})
#        return result

    def query(self,itemid,*subitemid):
        miUtils = utils(self.context)
        catalog = miUtils.catalog
        portal = miUtils.portal
        portal = portal.getId()
        path = '/'+ portal + '/' + itemid + '/' + '/'.join(subitemid)
        if len(subitemid)>0:
            path = path
        else:
            path = path[0:-1]
        result = catalog.searchResults(path={'query':path,'depth':1},portal_type=('Folder','Pagina2','Document','Tramite','Descentralizada'))
        return result

    def isAnon(self):
        """retorna el usuario anonymo"""
        plone_tools = getMultiAdapter((self.context, self.request), name=u'plone_tools')
        members = plone_tools.membership()
        anonymous = members.isAnonymousUser()
        return anonymous


class menuSlide (ViewletBase):
    """Viewlet menu.slide"""
    render = ViewPageTemplateFile('templates/slide.pt')
    def pics(self):
        miUtils = utils(self.context)
        catalog = miUtils.catalog
        portal = miUtils.portal
        portal = portal.getId()
        path = '/'+portal+'/slide'
        result = catalog.searchResults(path={'query':path,'depth':1},portal_type=('Image'))
        return result

class menuMultimedia(ViewletBase):
    """Viewlet menu.multimedia inside portal footer"""
    render =  ViewPageTemplateFile('templates/multimedia.pt')
    def gallerys(self):
        self.primeraFoto = []
        miUtils = utils(self.context)
        catalog = miUtils.catalog
        portal = miUtils.portal
        portal = portal.getId()
        path = '/'+portal+'/galeria-de-fotos'
        result = catalog.searchResults(path={'query':path,'depth':1},portal_type='Folder',
                                       sort_on='Date')
        for item in result:
            try:
                adapter = getGalleryAdapter(item.getObject(),self.request)
                self.primeraFoto.append(adapter.get_random_image())
            except:
                None

        return result

    def videos(self):
        """Retorna los videos del portal"""
        miUtils = utils(self.context)
        catalog = miUtils.catalog
        portal = miUtils.portal
        portal = portal.getId()
        path = '/'+portal+'/galeria-de-videos'
        result = catalog.searchResults(path={'query':path,'depth':1},portal_type=('RTInternalVideo','RTRemoteVideo'),
                                     sort_on='Date')
        return result

    def imgRemote(self,url):
        """Retorna la imagen thumb del
        video youtube"""

        videoId = re.match('http://.+/.+=(\w{11})(.+)*',url)
        imageremote = 'http://img.youtube.com/vi/' + videoId.group(1) + '/default.jpg'
        return imageremote

    def isAnon(self):
        """retorna el usuario anonymo"""
        plone_tools = getMultiAdapter((self.context, self.request), name=u'plone_tools')
        members = plone_tools.membership()
        anonymous = members.isAnonymousUser()
        return anonymous

    def banners(self):
        banners = {('banner_enlaces.jpg','Enlaces Relacionados'):'enlaces-relacionados',
                   ('banner_indica.jpg','Indicadores'):'odm'}
        miUtils = utils(self.context)
        portal = miUtils.portal
        portal_url = miUtils.portalUrl

        existing = portal.contentIds()
        for banner in banners.keys():
            if banners[banner] in existing:
                banners[banner] = portal_url + '/' + banners[banner]
            else:
                banners.pop(banner)

#       if (portal_url.find('gob')>=0):
        urlMunicipio = re.match("http://(www.)?([A-Za-z]+)(.gob)",portal_url)

        if urlMunicipio is not None:
            url = urlMunicipio.group(2)
        else:
            url = 'elrama'
            
        banners[('banner_municipio.jpg','Ir a Municipio')] = 'http://www.' + url + '.info.ni'
        return banners

class ploneFooter(ViewletBase):
    """Viewlet plone.footer """
    render =  ViewPageTemplateFile('templates/footer.pt')
    def footer(self):
        miutils = utils(self.context)
        return miutils.portalUrl

class ploneColophon(ViewletBase):
    """Viewlet plone.colophon """
    render =  ViewPageTemplateFile('templates/colophon.pt')
    def colophonContent(self):
        miUtils = utils(self.context)
        catalog = miUtils.catalog
        portal = miUtils.portal
        portal = portal.getId()
        pathSurvey = '/'+portal+'/encuestas'
        self.resultSurveys = catalog.searchResults(path={'query':pathSurvey,'depth':1},portal_type='PlonePopoll',sort_on='Date')

        pathBlog = '/'+portal
        self.resultBlogs = catalog.searchResults(path={'query':pathBlog},portal_type='BlogEntry',sort_on='Date')

        pathEvent = '/'+portal+'/eventos'
        self.resultEvents = catalog.searchResults(path={'query':pathEvent},portal_type='Event',sort_on='Date')
    
        return miUtils.portalUrl


class utils:
    """
    clase que contiene utiles como portal_catalog, portal root, etc
    """
    def __init__(self,context):
        self.context = context
        self.catalog = getToolByName(self.context,'portal_catalog')
        self.portal = getSite()
        self.portalUrl = self.portal.absolute_url()
